package com.mobilesalon.activity;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mobilesalon.MobileSalonFactory;
import com.mobilesalon.R;
import com.mobilesalon.business.ConfigurationException;
import com.mobilesalon.business.ServiceClientManager;
import com.mobilesalon.model.AppointmentBean;
import com.mobilesalon.provider.ServiceClientContract.Appointment;
import com.mobilesalon.tools.DateTools;
import com.mobilesalon.tools.MyCursorAdapter;
import com.mobilesalon.widget.swipe.SwipeListActivity;

public class Main extends SwipeListActivity {
	private static final String TAG = Main.class.getName();

	static final int PICK_CONTACT = 1;
	static final int SHOW_SERICE_DIALOG = 2;

	private ServiceClientManager serviceClientManager;

	private List<AppointmentBean> dailyAppointments;

	private Calendar current;

	private TextView titleTextView;
	private TextView totalAmountTextView;

	public Main() {
	}

	//
	// Lifecycle
	//
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.e(TAG, "Start Activity");
		super.onCreate(savedInstanceState);

		// business services
		serviceClientManager = MobileSalonFactory.getServiceClientManager();

		// UI
		setContentView(R.layout.main);
		titleTextView = (TextView) this.findViewById(R.id.service_daily_text_header);
		totalAmountTextView = (TextView) this.findViewById(R.id.service_daily_amount_total);

		current = Calendar.getInstance();

		
	}

	@Override
	public void onResume() {
		super.onResume();
		this.displayDailyAppointments();
	}

	private void displayDailyAppointments() {
		String day = DateTools.DATE_DATEFORMAT.format(current.getTime());

		Log.d(TAG, "Display report for date:" + day);
		titleTextView.setText(String.format(getString(R.string.title_daily_summary), day));

		try {
			this.dailyAppointments = serviceClientManager.fetchDailyAppointments(current);
		} catch (ConfigurationException e) {
			this.dailyAppointments = Collections.emptyList();
			Toast.makeText(MobileSalonFactory.getContext(), e.getErrorMessageRessourceId(),
					Toast.LENGTH_LONG).show();
		}

		// create cursor
		MatrixCursor dailyAppointmentCursor = new MatrixCursor(new String[] { Appointment._ID,
				Appointment.CLIENT_DISPLAY_NAME, Appointment.DATE, "sum" });
		this.startManagingCursor(dailyAppointmentCursor);

		// fill cursor with bean and compute totalAmount
		float totalAmount = 0;

		for (AppointmentBean appointmentBean : dailyAppointments) {
			dailyAppointmentCursor.addRow(new Object[] { appointmentBean.getId(),
					appointmentBean.getClientDisplayName(),
					appointmentBean.getDate().getTimeInMillis(), appointmentBean.getPrice() });
			totalAmount = totalAmount + appointmentBean.getPrice();
		}

		totalAmountTextView.setText("" + totalAmount);

		// Create a mapping between database columns and layout fields
		String[] from = new String[] { Appointment.CLIENT_DISPLAY_NAME, Appointment.DATE, "sum" };
		int[] to = new int[] { R.id.service_client_appointment_row_display_name,
				R.id.service_client_appointment_row_time,
				R.id.service_client_appointment_row_amount };

		// Create a cursor adapter and set it to display using a row layout
		MyCursorAdapter adapter = new MyCursorAdapter(this,
				R.layout.service_client_appointment_row, dailyAppointmentCursor, from, to);
		// special convertion for date
		adapter.addDateFormatFromLong(Appointment.DATE, R.id.service_client_appointment_row_time,
				DateTools.TIME_DATEFORMAT);

		setListAdapter(adapter);

	}

	//
	// Swipe management
	//
	public void swipeLeft() {
		current.add(Calendar.DATE, +1);
		this.displayDailyAppointments();
	}

	public void swipeRight() {
		current.add(Calendar.DATE, -1);
		this.displayDailyAppointments();
	}

	//
	// Triggered activities
	//
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.i(TAG, l.getAdapter().getItem(position).toString());

		AppointmentBean selectedAppointmentBean = dailyAppointments.get(position);
		Intent intent = new Intent(getApplicationContext(), AppointmentDetails.class);
		intent.putExtra("appointmentBean", selectedAppointmentBean);
		this.startActivity(intent);

	}

	//
	// Menu behavior
	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_main_settings:
			// start ServiceAdderActivity
			this.startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
			return true;
		case R.id.menu_main_reports:
			this.startActivity(new Intent(getApplicationContext(), MainReport.class));
			// return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}